#include "movingobject.h"
#include <QPixmap>
#include <QRect>

MovingObject::MovingObject(const QString &imagePath, QWidget *parent) : QObject(parent)
{    label=new QLabel(parent);
    //label = std::make_unique<QLabel>(parent);
    QPixmap objectPixmap(imagePath); // 加载传入的图片
    objectPixmap = objectPixmap.scaled(100, 110, Qt::KeepAspectRatio); // 调整图片大小
    label->setStyleSheet("background: transparent;");
    label->setPixmap(objectPixmap);
    label->adjustSize();
    label->setMask(objectPixmap.mask());
    moveTimer = new QTimer(this);
    connect(moveTimer, &QTimer::timeout, this, &MovingObject::moveObject); // 连接定时器和移动逻辑
}

MovingObject::~MovingObject()
{
    //delete label; // 释放 QLabel
    //delete moveTimer; // 释放定时器
    //if(label){label->deleteLater();}
}

void MovingObject::startMoving()
{
    collisionDetected = false;

    moveTimer->start(3); // 启动定时器，每 10ms 移动一次
}

void MovingObject::stopMoving()
{if (moveTimer)
    moveTimer->stop(); // 停止定时器
}

void MovingObject::moveObject()
{
    if (collisionDetected) {
        return; // 如果发生碰撞，停止移动
    }

    if (objectX > targetX) {
        objectX -= 1; // 向左移动
    }
    if (objectY > targetY) {
        objectY -= 1; // 向上移动
    }

    label->move(objectX, objectY); // 更新物体位置

    /*if (objectX <= 200) {
        label->hide(); // 隐藏物体
        label->deleteLater(); // 销毁物体
    }*/
}

void MovingObject::checkCollision(const QRect &manRect) {
    QRect objectRect = label->geometry(); // 获取物体的矩形区域

    // 检测是否与跑步小人碰撞
    if (manRect.intersects(objectRect)) {
        collisionDetected = true; // 发生碰撞
        stopMoving(); // 停止移动
    }
}
